local sk__tianji = fk.CreateSkill {

  name = "sk__tianji",

  tags = {},

}



sk__tianji:addEffect(fk.EventPhaseStart, {
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(sk__tianji.name) and target.phase == Player.Play
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if room.draw_pile == 0 then
      room:shuffleDrawPile()
      if room.draw_pile == 0 then
        room:gameOver("")
      end
    end
    if player.dead then return end
    if table.every(room.alive_players, function(p)
          return player:getHandcardNum() >= p:getHandcardNum()
        end) then
      local result = room:askToExchange(player, {
        piles = { room:getNCards(1), player:getCardIds("h") },
        piles_name = { "Top", player.general },
        skill_name = sk__tianji.name,
      })
      if #result == 2 then
        local card = result[1]
        if table.contains(player:getCardIds("h"), result[2]) then
          card = result[2]
        end
        room:swapCardsWithPile(player, card, room:getNCards(1), sk__tianji.name, "Top", false)
      end
    else
      local choice = room:askToViewCardsAndChoice(player, {
        cards = room:getNCards(1),
        choices = { "OK", "Cancel" },
        skill_name = sk__tianji.name,
        prompt = "#sk__tianji-choice"
      })
      if choice == "OK" then
        room:moveCardTo(room.draw_pile[1], Card.PlayerHand, player, fk.ReasonJustMove, sk__tianji.name, nil, false,
          player)
      end
    end
  end,
})

return sk__tianji
